import {createRouter, createWebHashHistory} from 'vue-router'
import {routes} from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })
const isEmpty = (obj) => {
  return Object.keys(obj).length === 0
}
const router = createRouter({
  history: createWebHashHistory(), // hash模式
  // history: createWebHistory(),// HTML5模式
  routes: [...routes],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
})
// 导航守卫
router.beforeEach((to, from, next) => {
  console.log('to', to)
  console.log('to.path', to.path)
  NProgress.start()
  document.title = to.meta && isEmpty(to.meta) ? '首页' : to.meta.title

  if (to.path === '/error') {
    next('/')
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
